"""
客户留言管理视图
"""

from rest_framework import viewsets, filters, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema, extend_schema_view

from pecco_site.models import ContactMessage
from ..serializers.contact_message import ContactMessageSerializer, ContactMessageDetailSerializer
from ..permissions import IsAdminUser


@extend_schema_view(
    list=extend_schema(summary='获取客户留言列表', tags=['客户留言管理']),
    retrieve=extend_schema(summary='获取客户留言详情', tags=['客户留言管理']),
    update=extend_schema(summary='更新客户留言', tags=['客户留言管理']),
    partial_update=extend_schema(summary='部分更新客户留言', tags=['客户留言管理']),
    destroy=extend_schema(summary='删除客户留言', tags=['客户留言管理']),
)
class ContactMessageViewSet(viewsets.ModelViewSet):
    """客户留言管理 ViewSet"""
    queryset = ContactMessage.objects.all().order_by('-created_at')
    permission_classes = [IsAuthenticated, IsAdminUser]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['message_type', 'is_read']
    search_fields = ['name', 'email', 'message']
    ordering_fields = ['created_at', 'is_read']
    ordering = ['-created_at']
    
    def get_serializer_class(self):
        if self.action == 'retrieve':
            return ContactMessageDetailSerializer
        return ContactMessageSerializer
    
    def has_add_permission(self):
        """不允许在后台手动添加留言"""
        return False
    
    def create(self, request, *args, **kwargs):
        """禁止创建"""
        return Response(
            {'detail': '不允许在后台手动添加留言'},
            status=status.HTTP_403_FORBIDDEN
        )
    
    @action(detail=True, methods=['patch'])
    def mark_read(self, request, pk=None):
        """标记为已读"""
        message = self.get_object()
        message.is_read = True
        message.save()
        serializer = self.get_serializer(message)
        return Response(serializer.data)
    
    @action(detail=True, methods=['patch'])
    def mark_unread(self, request, pk=None):
        """标记为未读"""
        message = self.get_object()
        message.is_read = False
        message.save()
        serializer = self.get_serializer(message)
        return Response(serializer.data)
    
    @action(detail=False, methods=['get'])
    def stats(self, request):
        """获取统计信息"""
        total = ContactMessage.objects.count()
        unread = ContactMessage.objects.filter(is_read=False).count()
        
        # 按类型统计
        by_type = {}
        for choice in ContactMessage.MESSAGE_TYPES:
            type_code = choice[0]
            type_name = choice[1]
            count = ContactMessage.objects.filter(message_type=type_code).count()
            by_type[type_code] = {
                'name': type_name,
                'count': count
            }
        
        return Response({
            'total': total,
            'unread': unread,
            'by_type': by_type
        })

